// 确保DOM加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // DOM元素
    const searchIdInput = document.getElementById('searchIdInput');
    const searchIdButton = document.getElementById('searchIdButton');
    const searchResult = document.getElementById('searchResult');

    // 状态选项映射（使用数字键与API返回值匹配）
    const statusOptions = {
        '0': '待审核',
        '1': '已通过',
        '2': '已拒绝'
    };

    // 年级和班级选项映射
    const gradeOptions = {
        '1': '一年级',
        '2': '二年级',
        '3': '三年级',
        '4': '四年级',
        '5': '五年级',
        '6': '六年级',
        '7': '七年级',
        '8': '八年级',
        '9': '九年级'
    };

    const classOptions = {
        '1': '1班',
        '2': '2班',
        '3': '3班',
        '4': '4班',
        '5': '5班'
    };

    const categoryOptions = {
        '1': '校园故事',
        '2': '学习心得',
        '3': '科技创新',
        '4': '艺术文化',
        '5': '体育活动',
        '6': '其他'
    };

    // 查询按钮点击事件
    searchIdButton.addEventListener('click', async () => {
    const id = searchIdInput.value.trim();
    
    if (!id) {
        showMessage('请输入投稿ID', 'error');
        return;
    }
    
    try {
        // 清空之前的结果
        searchResult.innerHTML = '<div class="loading">正在查询中...</div>';
        
        // 调用API查询投稿信息
        const response = await fetch(`/api/submissions/${id}`);
        
        if (!response.ok) {
            if (response.status === 404) {
                showMessage('未找到该投稿信息', 'error');
            } else {
                showMessage('查询失败，请稍后重试', 'error');
            }
            return;
        }
        
        const result = await response.json();
        
        // 检查响应结构，从data字段中提取投稿信息
        if (result.success && result.data) {
            // 渲染查询结果
            renderSearchResult(result.data);
        } else {
            showMessage('获取的数据格式错误', 'error');
        }
        
    } catch (error) {
        console.error('查询错误:', error);
        showMessage('查询过程中出现错误，请稍后重试', 'error');
    }
});

    // 回车键触发查询
    searchIdInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            searchIdButton.click();
        }
    });

    // 渲染查询结果
    function renderSearchResult(submission) {
        // 检查submission是否有效且为对象
        if (!submission || typeof submission !== 'object') {
            showMessage('返回的数据格式不正确', 'error');
            return;
        }
        
        // 安全获取字段值，提供默认值
        const id = submission.id ?? '未知';
        const grade = submission.grade ?? '';
        const classValue = submission.class ?? '';
        const name = submission.name ?? '未知';
        const title = submission.title ?? '未提供';
        const category = submission.category ?? '';
        const status = submission.status ?? '未知';
        const submittedAt = submission.submittedAt;
        
        // 根据数字状态码设置对应的样式类
        const statusClass = status === '1' ? 'status-approved' : 
                           status === '2' ? 'status-rejected' : 'status-pending';
        
        // 安全格式化日期
        let formattedDate = '未提供';
        if (submittedAt) {
            try {
                formattedDate = new Date(submittedAt).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (e) {
                formattedDate = '日期格式错误';
            }
        }
        
        searchResult.innerHTML = `
            <div class="result-card">
                <div class="result-header">
                    <h3>投稿信息</h3>
                    <span class="result-id">ID: ${id}</span>
                </div>
                <div class="result-content">
                    <div class="result-row">
                        <span class="result-label">投稿人:</span>
                        <span class="result-value">${gradeOptions[grade] || ''} ${classOptions[classValue] || ''} ${name}</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">标题:</span>
                        <span class="result-value">${title}</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">分类:</span>
                        <span class="result-value">${categoryOptions[category] || category || '未提供'}</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">提交时间:</span>
                        <span class="result-value">${formattedDate}</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">审核状态:</span>
                        <span class="result-value ${statusClass}">${statusOptions[status] || status}</span>
                    </div>
                </div>
            </div>
        `;
    }
});



// 显示消息
function showMessage(message, type = 'info') {
    const searchResult = document.getElementById('searchResult');
    searchResult.innerHTML = `
        <div class="message ${type}">
            ${message}
        </div>
    `;
    
    // 如果是错误消息，3秒后自动清除
    if (type === 'error') {
        setTimeout(() => {
            searchResult.innerHTML = '';
        }, 3000);
    }
}